package com.jinsilu.freight.ui.activity;

import android.content.Intent;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.BusUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.jinsilu.freight.R;
import com.jinsilu.freight.common.MyActivity;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.request.DeleteCarApi;
import com.jinsilu.freight.http.request.GetVehicleListApi;
import com.jinsilu.freight.http.request.SetDefaultCarApi;
import com.jinsilu.freight.http.response.VehicleListBean;
import com.jinsilu.freight.ui.adapter.VehicleListAdapter;
import com.jinsilu.freight.ui.dialog.MenuDialog;
import com.jinsilu.freight.ui.dialog.MessageDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的车辆管理页面
 *
 * @author yangyang
 * @time 2020-11-10 15:49
 */
public class MyVehicleManageActivity extends MyActivity {

    private SmartRefreshLayout refresh;
    private RecyclerView recycler;
    private VehicleListAdapter mAdapter;

    private Integer mCurrentPage = 1;

    private List<String> mDialogDataList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_vehicle_manage;
    }

    @Override
    protected void initView() {

        refresh = findViewById(R.id.refresh);
        refresh.setEnableRefresh(true);
        refresh.setEnableLoadMore(false);

        recycler = findViewById(R.id.recycler);

        recycler.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerDecoration.builder(getContext())
                .asSpace().size(10, TypedValue.COMPLEX_UNIT_DIP)
                .showSideDividers()
                .showFirstDivider()
                .showLastDivider()
                .build()
                .addTo(recycler);
        mAdapter = new VehicleListAdapter(new ArrayList<>());
        mAdapter.addFooterView(getFooter(v -> {
            // 添加车辆
            startActivityForResult(MyVehicleAddActivity.class, (resultCode, data) -> {
                // 如果已经添加成功
                if (resultCode == RESULT_OK) {
                    getVehicleList();
                }
            });
        }));
        recycler.setAdapter(mAdapter);

        mAdapter.setEmptyView(R.layout.layout_empty_data_view);

        mAdapter.addChildClickViewIds(R.id.vehicle_card_operate);
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                VehicleListBean vehicleListBean = (VehicleListBean) adapter.getData().get(position);
                String authStatus = vehicleListBean.getAuthStatus();
                mDialogDataList.clear();
                if ("1".equals(authStatus)) {
                    mDialogDataList.add("设置当前使用");
                } else {
                    mDialogDataList.add("修改");
                }

                mDialogDataList.add("删除");


                // 底部选择框
                new MenuDialog.Builder(view.getContext())
                        // 设置 null 表示不显示取消按钮
                        //.setCancel(getString(R.string.common_cancel))
                        // 设置点击按钮后不关闭对话框
                        //.setAutoDismiss(false)
                        .setList(mDialogDataList)
                        .setListener(new MenuDialog.OnListener<String>() {

                            @Override
                            public void onSelected(BaseDialog dialog, int position, String string) {
                                if ("1".equals(authStatus)) {
                                    switch (position) {
                                        case 0:
                                            setDefaultVehicle(vehicleListBean);
                                            break;
                                        case 1:
                                            deleteVehicle(vehicleListBean);
                                            break;
                                    }
                                } else {
                                    switch (position) {
                                        case 0:
                                            Intent intent = new Intent(MyVehicleManageActivity.this, MyVehicleAddActivity.class);
                                            intent.putExtra("vehicle", vehicleListBean.getVehicleId());
                                            startActivityForResult(intent, (resultCode, data) -> {
                                                if (RESULT_OK == resultCode) {
                                                    getVehicleList();
                                                }
                                            });
                                            break;
                                        case 1:
                                            new MessageDialog.Builder(dialog.getActivity())
                                                    // 标题可以不用填写
                                                    .setTitle("")
                                                    // 内容必须要填写
                                                    .setMessage("是否确认删除？")
                                                    // 确定按钮文本
                                                    .setConfirm(getString(R.string.common_confirm))
                                                    // 设置 null 表示不显示取消按钮
                                                    .setCancel(getString(R.string.common_cancel))
                                                    // 设置点击按钮后不关闭对话框
                                                    //.setAutoDismiss(false)
                                                    .setListener(new MessageDialog.OnListener() {

                                                        @Override
                                                        public void onConfirm(BaseDialog dialog) {
                                                            deleteVehicle(vehicleListBean);
                                                        }

                                                        @Override
                                                        public void onCancel(BaseDialog dialog) {

                                                        }
                                                    })
                                                    .show();
                                            break;
                                    }
                                }
                            }

                            @Override
                            public void onCancel(BaseDialog dialog) {

                            }
                        })
                        .show();
            }
        });
    }

    @Override
    protected void initData() {
        getVehicleList();
    }

    private void getVehicleList() {
        // 车辆列表
        EasyHttp.get(this)
                .api(new GetVehicleListApi().setPageNum(String.valueOf(mCurrentPage)).setPageSize("10"))
                .request(new HttpCallback<HttpData<VehicleListBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<VehicleListBean> data) {
                        List<VehicleListBean> vehicleListBeans = data.getRows();
                        mAdapter.setList(vehicleListBeans);
                    }
                });
    }

    private void setDefaultVehicle(VehicleListBean vehicleListBean) {
        // 设置默认车辆
        EasyHttp.put(this)
                .api(String.format("api/certification/default/vehicle/%s", vehicleListBean.getVehicleId()))
                .request(new HttpCallback<HttpData<Void>>(this) {

                    @Override
                    public void onSucceed(HttpData<Void> data) {
                        // 本地设置默认车辆
//                        for (VehicleListBean bean :
//                                mAdapter.getData()) {
//                            if (bean.getVehicleId().equals(vehicleListBean.getVehicleId())) {
//                                bean.setDefaultVehicle("1");
//                            } else {
//                                bean.setDefaultVehicle("0");
//                            }
//                        }
                        toast(data.getMessage());
                        getVehicleList();
                        BusUtils.postSticky(HomeActivity.TAG_REFRESH_USER_DATA); // UnfinishedWaybillFragment will receive
//                        mAdapter.notifyDataSetChanged();
                    }
                });
    }

    private void deleteVehicle(VehicleListBean vehicleListBean) {
        // 删除车辆
        EasyHttp.delete(this)
                .api(String.format("api/certification/vehicle/%s", vehicleListBean.getVehicleId()))
                .request(new HttpCallback<HttpData<Void>>(this) {

                    @Override
                    public void onSucceed(HttpData<Void> data) {
                        mAdapter.remove(vehicleListBean);
                    }
                });
    }

    private View getFooter(View.OnClickListener listener) {
        View footer = LayoutInflater.from(this).inflate(R.layout.footer_of_vehicle_list, recycler, false);
        footer.setOnClickListener(listener);
        return footer;
    }
}
